package com.cskaoyan.login;

import com.cskaoyan.FirstJDBC;

import java.sql.*;

/**
 * 创建日期: 2022/08/25 15:57
 *
 * @author ciggar
 *
 *         // 根据用户名和密码查询数据库，
 *         // 假如查到了，说明用户名和密码正确，登录成功
 *         // 假如没有查到，说明不正确，登录失败
 */
public class LoginDemo {


    public static void main(String[] args) throws SQLException {

        Boolean ret = loginUsePreparedStatement("张飞", "sdhdfjf' or '1=1");

//        Boolean ret = login("张飞","sdhdfjf' or '1=1");

        // select * from user where username = 'aaa' and password = 'bbb';

        // select * from user where username = 'aaa' and password = 'sdhdfjf' or '1=1';

        if (ret){
            System.out.println("登录成功！");
        }else {
            System.out.println("登录失败！");
        }


    }


    // 登录的方法
    public static Boolean login(String username,String password) throws SQLException {

        // 注册驱动
//        DriverManager.registerDriver(new Driver());

        // 获取连接
        Connection connection = DriverManager.getConnection(FirstJDBC.url, FirstJDBC.username, FirstJDBC.password);

        // 获取statement对象
        Statement statement = connection.createStatement();

        String sql = "select * from user where username = '"+username+"' and password = '"+ password + "'";

        System.out.println("sql:" +sql);

        // 执行SQL语句
        ResultSet resultSet = statement.executeQuery(sql);

        // 判断
        if (resultSet.next()) {
            return true;
        }
        else {
            return false;
        }
    }



    // 安全的登录
    public static boolean loginUsePreparedStatement(String username,String password) throws SQLException {

        // 注册驱动
//        DriverManager.registerDriver(new Driver());

        // 获取连接
        Connection connection = DriverManager.getConnection(FirstJDBC.url, FirstJDBC.username, FirstJDBC.password);


        // 创建PreparedStatement对象
        PreparedStatement prepareStatement = connection.prepareStatement("select * from user where username = ? and password = ?");


        // 传参
        prepareStatement.setString(1,username);
        prepareStatement.setString(2,password);

        // 真正的把SQL语句中缺失的参数传递给MySQL服务器
        ResultSet resultSet = prepareStatement.executeQuery();

        if (resultSet.next()) {
            return true;
        }else {
            return false;
        }


    }
}
